package com.sky.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.exception.OrderBusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 百度地图工具类
 */
@Component
public class BaiduMapUtil {
     //百度地图ak
     @Value("${sky.baidu.ak}")
     private String AK;
     //获取经纬度请求路径
     private static final String COORDINATE__URL="https://api.map.baidu.com/geocoding/v3";
     //路径规划请求路径
     private static final String ROUTE_URL="https://api.map.baidu.com/direction/v2/riding?";

    /**
     * 根据地址获取经纬度
     * @param address
     * @return
     */
    public String getLngLat(String address) {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", AK);
        String coordinate = HttpClientUtil.doGet(COORDINATE__URL, params);
        JSONObject jsonObject = JSONObject.parseObject(coordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("获取地址信息失败");
        }
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String LatLng = location.getString("lat") + "," + location.getString("lng");
        return LatLng;
    }

    public Integer getDistance(String origin, String destination) {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("origin", origin);
        params.put("destination", destination);
        params.put("ak", AK);
        params.put("output", "json");
        String route = HttpClientUtil.doGet(ROUTE_URL, params);
        JSONObject jsonObject = JSONObject.parseObject(route);
        if (StringUtils.isBlank(route)) {
            throw new OrderBusinessException("获取路径距离失败");
        }
        if (jsonObject.getString("status").equals("2002")){
            throw new OrderBusinessException("距离过远");
        }

        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("获取路径距离失败");
        }
        JSONObject jsonObject1 = (JSONObject) jsonObject.getJSONObject("result").getJSONArray("routes").get(0);
        Integer distance = Integer.valueOf(jsonObject1.getString("distance"));
        return distance;
    }

}
